package com.whfc.ms.api.mach.service.impl;

import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.result.PageData;
import com.whfc.common.util.RandomUtil;
import com.whfc.entity.dto.OssPathDTO;
import com.whfc.mach.dto.MachFileDTO;
import com.whfc.mach.param.MachFileAddParam;
import com.whfc.mach.param.MachFileRenameParam;
import com.whfc.mach.service.AppMachFileService;
import com.whfc.ms.api.mach.service.MsMachFileService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author sun_guodong
 * @description
 * @date 2021-04-07
 */
@Service
public class MsMachFileServiceImpl implements MsMachFileService {

    @DubboReference(interfaceClass = AppMachFileService.class, version = "1.0.0")
    private AppMachFileService appMachFileService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 设备文件路径
     */
    private String machFilePath = "mach/file";

    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private FilePathConfig filePathConfig;

    @Override
    public PageData<MachFileDTO> list(Integer machId, Integer pageNum, Integer pageSize) {
        return appMachFileService.list(machId, pageNum, pageSize);
    }

    @Override
    public void add(MachFileAddParam param) {
        appMachFileService.add(param);
    }

    @Override
    public void rename(MachFileRenameParam param) {
        appMachFileService.rename(param);
    }

    @Override
    public void del(Integer fileId) {
        appMachFileService.del(fileId);
    }

    @Override
    public OssPathDTO upload(MultipartFile file) {
        // 先将文件上传到服务器上
        String url = "";
        try {
            String originalFilename = file.getOriginalFilename();
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = RandomUtil.getRandomFileName() + postfix;
            String ossKey = filePathConfig.getFilePath(machFilePath, fileName);
            url = fileHandler.upload(ossKey, file.getInputStream());
        } catch (Exception e) {
            logger.info("上传设备档案文件失败,{}", e);
        }
        return new OssPathDTO(url);
    }
}
